﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Production_Set.API.Application.Commands.Customerser;
using Production_Set.API.Application.Commands.Orderers;
using Production_Set.API.Application.Commands.Resourctes;
using Production_Set.API.Application.Commands.Warehousings;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Globalization;
using System.Security.Cryptography;
using THE_WIND_RISES.Common.Domans.Produce.Customers;
using THE_WIND_RISES.Common.Dtos;

namespace Production_Set.API.Controllers.LEO
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductionLeo : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<ProductionLeo> logger;
        private readonly IBaseRepository<Customer> Customer;


        public ProductionLeo(IMediator mediator, ILogger<ProductionLeo> logger, IBaseRepository<Customer> customer)
        {
            this.mediator = mediator;
            this.logger = logger;
            this.Customer = customer;
        }


        /// <summary>
        /// 资源管理添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetResourceAdd(ResourceCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("资源管理添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("资源管理添加失败");
                throw;
            }
        }

        /// <summary>
        /// 资源管理删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetResourceDelete(ResourceDeleteCommend cmd)
        {
            try
            {
                logger.LogInformation("资源管理删除成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("资源管理删除失败");
                throw;
            }
        }

        /// <summary>
        /// 审批
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetResourceState(ResourceStateCommend cmd)
        {
            try
            {
                logger.LogInformation("资源管理审批成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("资源管理审批失败");
                throw;
            }
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetResourceSubmit(ResourceSubmitCommend cmd)
        {
            try
            {
                logger.LogInformation("资源管理提交成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("资源管理提交失败");
                throw;
            }
        }

        /// <summary>
        /// 驳回
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetResourceOverrule(ResourceOverruleCommend cmd)
        {
            try
            {
                logger.LogInformation("资源管理驳回成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("资源管理驳回失败");
                throw;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetResourceUpdate(ResourceUpdateCommend cmd)
        {
            try
            {
                logger.LogInformation("资源管理修改成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("资源管理修改失败");
                throw;
            }
            
        }

        /// <summary>
        /// 客户添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetCustomerAdd(CustomerCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("客户添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("客户添加失败");
                throw;
            }
        }

        /// <summary>
        /// 客户删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetCustomerDel(CustomerDeleteCommend cmd)
        {
            try
            {
                logger.LogInformation("客户删除成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("客户删除失败");
                throw;
            }
        }
        

        /// <summary>
        /// 客户修改
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetCustomerUpdate(CustomerUpdateCommend cmd)
        {
            try
            {
                logger.LogInformation("客户修改成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("客户修改失败");
                throw;
            }
        }

        /// <summary>
        /// 销售订单添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOrdersAdd(OrdersCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("销售订单添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("销售订单添加失败");
                throw;
            }
        }

        /// <summary>
        /// 销售订单修改
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOrdersUpdate(OrdersUpdateCommend cmd)
        {
            try
            {
                logger.LogInformation("销售订单修改成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("销售订单修改失败");
                throw;
            }
        }

        /// <summary>
        /// 销售订单审批
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOrdersState(OrdersStateCommend cmd)
        {
            try
            {
                logger.LogInformation("销售订单审批成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("销售订单审批失败");
                throw;
            }
        }

        /// <summary>
        /// 销售订单提交
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetROrdersSubmit(OrdersSubmitCommend cmd)
        {
            try
            {
                logger.LogInformation("销售订单提交成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("销售订单提交失败");
                throw;
            }
        }

        /// <summary>
        /// 销售订单驳回
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOrdersOverrule(OrdersOverruleCommend cmd)
        {
            try
            {
                logger.LogInformation("销售订单驳回成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("销售订单驳回失败");
                throw;
            }
        }

        /// <summary>
        /// 订单行添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOrdersLineAdd(OrderLineCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("订单行添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("订单行添加失败");
                throw;
            }
        }

        /// <summary>
        /// 订单行删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOrdersLineDel(OrderLineDelCommend cmd)
        {
            try
            {
                logger.LogInformation("订单行删除成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("订单行删除失败");
                throw;
            }
        }

        /// <summary>
        /// 订单行修改
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOrdersLineUpdate(OrderLineUpdateCommend cmd)
        {
            try
            {
                logger.LogInformation("订单行修改成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("订单行修改失败");
                throw;
            }
        }

        #region 导入导出
        /// <summary>
        /// 客户导入
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public dynamic GetImport(IFormFile file)
        {
            var result = new Result() { Code = (int)CommonErrorCodes.Search };
            //获取文件扩展名 判断上传的文件类型是否正确
            var ext = Path.GetExtension(file.FileName);
            if (ext == ".xls" || ext == ".xlsx")
            {

            }
            else
            {
                return "您上传的文件类型不正确";
            }

            using (MemoryStream ms = new MemoryStream())
            {
                file.CopyTo(ms);
                ms.Position = 0;

                //根据文件扩展名创建对应的工作簿对象(HSSFWorkbook用于.xls，XSSFWorkbook用于.xlsx)
                //获取工作簿
                IWorkbook wb = null;
                if (ext == ".xls")//创建97-2003
                {
                    wb = new HSSFWorkbook(ms);
                }
                else//创建2007及以上版本
                {
                    wb = new XSSFWorkbook(ms);
                }

                //获取sheet 获取工作簿中的第一个工作表
                ISheet sheet = wb.GetSheetAt(0);

                int totalRows = sheet.LastRowNum;//总行数
                int totalCells = sheet.GetRow(0).LastCellNum;//总列数

                // 创建一个用于存储解析后的数据的列表
                var farrowingsList = new List<CustomerDto>();

                //循环总行数 开头必须是1 不然从表头开始
                //遍历工作表的每一行（从第二行开始，因为第一行通常是表头）
                for (int i = 1; i <= totalCells; i++)
                {
                    //获取当前行
                    IRow row = sheet.GetRow(i);

                    //这个类必须写到循环里边 不然你批量添加只能添加一行 
                    var dto = new CustomerDto();// 在循环内创建新的对象实例

                    ////下标从0开始 导入时 外键需进行判断 客户不知道你是外键 只会输入文字 需要在后台判断
                    //var earnumber = row.GetCell(0).ToString();
                    //var basic = SalesDetails.GetAll().Where(z => z.SalesDetailsOrderNum == earnumber).FirstOrDefault();
                    //dto.CustomerId = basic.CustomerId;

                    //日期转换
                    //日期在excel表中必须是年月日格式 但不能加时分秒 (注意!!!!)
                    string inputDate = row.GetCell(17).ToString();
                    string[] multipleFormats = { "dd-M月-yyyy", "yyyy-M-dd" };
                    DateTime parsedDate;
                    foreach (var format in multipleFormats)
                    {
                        if (DateTime.TryParseExact(inputDate, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                        {
                            dto.HandleTime = Convert.ToDateTime(parsedDate.ToString("yyyy-MM-dd"));
                            break;//成功解析后跳出循环
                        }
                    }

                    dto.CustomerId = Convert.ToInt32(row.GetCell(0).ToString());
                    dto.CustomerNo = row.GetCell(1).ToString();
                    dto.CustomerName = row.GetCell(2).ToString();
                    dto.CustomerType = row.GetCell(3).ToString();
                    dto.CustomerPhone = row.GetCell(4).ToString();
                    dto.CustomerEmail = row.GetCell(5).ToString();
                    dto.IndustryId = Convert.ToInt32(row.GetCell(6).ToString());
                    dto.CustomerAddress = row.GetCell(7).ToString();
                    dto.CountryId = row.GetCell(8).ToString();
                    dto.CityId = row.GetCell(9).ToString();
                    dto.CustomerLabel = row.GetCell(10).ToString();
                    dto.CustomerLogotype = Convert.ToBoolean(row.GetCell(11).ToString() == "是" ? 1 : 0);
                    dto.CustomerState = Convert.ToBoolean(row.GetCell(12).ToString() == "有效" ? 1 : 0);
                    dto.ApprovalStatus = Convert.ToInt32(row.GetCell(13).ToString());
                    dto.IsDelete = Convert.ToBoolean(row.GetCell(14).ToString() == "false" ? 1 : 0);
                    dto.Handle = row.GetCell(15).ToString();
                    dto.HandleContext = row.GetCell(16).ToString();
                    dto.Pid = Convert.ToInt32(row.GetCell(18).ToString());


                    //添加到数据集合中
                    farrowingsList.Add(dto);
                }
                //跳出循环后 使用AddRange进行批量添加
                string sql = "insert into Customer values(@CustomerId,@CustomerNo,@CustomerName,@CustomerType,@CustomerPhone,@CustomerEmail,@IndustryId,@CustomerAddress," +
                "@CountryId,@CityId,@CustomerLabel,@CustomerLogotype,@CustomerState,@ApprovalStatus,@IsDelete,@Handle,@HandleContext,@HandleTime,@Pid);";
                var res = Customer.AddRound(sql, farrowingsList);
                //判断
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCodes.Success;
                    result.Msg = "导入成功";

                }
                else
                {
                    result.Msg = "导入失败";
                }

                return result;
            }
        }
        #endregion


        /// <summary>
        /// 入库添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetStorageCreate(StorageCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("入库添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("入库添加失败");
                throw;
            }
        }


        /// <summary>
        /// 入库修改
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetStorageUpdate(StorageUpdateCommend cmd)
        {
            try
            {
                logger.LogInformation("入库行修改成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("入库行修改失败");
                throw;
            }
        }

        /// <summary>
        /// 订单行添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOrderTineAdd(OrderTineCreateCommend cmd)
        {
            try
            {
                logger.LogInformation("订单行添加成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("订单行添加失败");
                throw;
            }
        }

        /// <summary>
        /// 订单行删除
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOrderTineDel(OrderTineDelCommend cmd)
        {
            try
            {
                logger.LogInformation("订单行删除成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("订单行删除失败");
                throw;
            }
        }

        /// <summary>
        /// 订单行修改
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> GetOrderTineUpdate(OrderTineUpdateCommend cmd)
        {
            try
            {
                logger.LogInformation("订单行修改成功");
                return await mediator.Send(cmd);
            }
            catch (Exception)
            {
                logger.LogError("订单行修改失败");
                throw;
            }
        }

    }
}
